from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.core.paginator import Paginator
from django.http      import HttpResponse, Http404, HttpResponseRedirect
from django.template  import RequestContext
from django.contrib.auth.decorators import login_required
from bb.models        import *
from bb.forms         import *
def common_processor(request):
    return {\
        "req":request,
    }

def index(request):
    dict_boards = []
    boards = Board.objects.filter(level__in=(0,1)).order_by('level')
    def install_sub(sub):
        parent = sub.parent
        for i in range(len(dict_boards)):
            if dict_boards[i]['board'] == parent:
                dict_boards[i]["sub"].append(sub)
        return False
        
    for board in boards:
        if board.level == 0:
            dict_boards.append( { "board" : board,
                                  "sub"   : [], } )
        if board.level == 1:
            install_sub(board)

    return render_to_response(\
        'bb/index.html',
        { "boards" : dict_boards },
        context_instance = RequestContext(request, processors=[common_processor]),
    )

def board(request, board_slug, page=None):
    board = get_object_or_404(Board, slug=board_slug)
    
    paginators = Paginator(
        Topic.objects.filter(board = board).order_by("-last_talk_datetime"),
        30,
    )
    if not page:
        page   = 1
    paginator  = paginators.page(page)
    
    return render_to_response(\
        'bb/board.html',
        {\
            "board"     : board,
            "paginator" : paginator,
        },
        context_instance = RequestContext(request, processors=[common_processor]),
    )

def topic(request, topic_id, page = None):
    topic = get_object_or_404(Topic, pk=topic_id)
    topic.hits += 1
    topic.save()

    talks = Talk.objects.filter(topic=topic_id).order_by("-created")

    if len(talks) == 0:
        raise Http404
        
    paginators = Paginator(
        talks,
        10,
    )
    if not page:
        page = 1
    paginator = paginators.page(page)
    return render_to_response(\
        'bb/topic.html',
        {\
            "talks":talks,
            "topic":topic,
        },
        context_instance = RequestContext(request, processors=[common_processor]),
    )

@login_required
def add_topic(request, board_slug):
    board = get_object_or_404(Board, slug=board_slug)
    user  = request.user
    ip    = request.META.get('REMOTE_ADDR', '')
    
    if request.method == "POST":
        form = TopicForm(request.POST, board=board, user=user, ip=ip)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(request.POST.get("next", ""))
    else:
        form = TopicForm()

    return render_to_response(\
        'bb/topic_add.html',
        { "form" : form, 'next':request.META.get("HTTP_REFERER", "") },
        context_instance = RequestContext(request, processors=[common_processor]),
    )

@login_required
def add_talk(request, topic_id):
    topic = get_object_or_404(Topic, pk=topic_id)
    board = topic.board
    user  = request.user
    ip    = request.META.get("REMOTE_ADDR", "")
    
    if request.method == "POST":
        form = TalkForm(request.POST, topic=topic, user=user, ip=ip, board=board)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(request.POST.get("next", ""))
    else:
        form = TalkForm()
        
    return render_to_response(\
        'bb/talk_add.html',
        { 'form':form, 'next':request.META.get("HTTP_REFERER", "") },
        context_instance = RequestContext(request, processors=[common_processor]),
    )
    
def member_register(request):
    return HttpResponse("")
